package com.hongtech.tiny.modules.oss.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hongtech.tiny.common.exception.CustomException;
import com.hongtech.tiny.modules.oss.entity.QiniuConfigEntity;
import com.hongtech.tiny.modules.oss.mapper.QiniuConfigMapper;
import com.hongtech.tiny.modules.oss.service.QiNiuConfigService;
import lombok.RequiredArgsConstructor;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@RequiredArgsConstructor
@CacheConfig(cacheNames = "qiNiu")
public class QiNiuConfigServiceImpl extends ServiceImpl<QiniuConfigMapper, QiniuConfigEntity> implements QiNiuConfigService {

    @Override
    @Cacheable(key = "'config'")
    public QiniuConfigEntity getConfig() {
        QiniuConfigEntity qiniuConfigEntity = getById(1L);
        return qiniuConfigEntity == null ? new QiniuConfigEntity() : qiniuConfigEntity;
    }

    @Override
    @CacheEvict(key = "'config'")
    @Transactional(rollbackFor = Exception.class)
    public void saveConfig(QiniuConfigEntity qiniuConfigEntity) {
        qiniuConfigEntity.setId(1L);
        String http = "http://";
        String https = "https://";
        if (!(qiniuConfigEntity.getHost().toLowerCase().startsWith(http)|| qiniuConfigEntity.getHost().toLowerCase().startsWith(https))) {
            throw new CustomException("外链域名必须以http://或者https://开头");
        }
        saveOrUpdate(qiniuConfigEntity);
    }

    @Override
    @CacheEvict(key = "'config'")
    @Transactional(rollbackFor = Exception.class)
    public void updateType(String type) {
        QiniuConfigEntity qiniuConfigEntity = getById(1L);
        qiniuConfigEntity.setType(type);
        saveOrUpdate(qiniuConfigEntity);
    }
}
